"""
基础发布器抽象类
"""

from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
from datetime import datetime

from ..core.logger import app_logger


class BasePublisher(ABC):
    """发布器基类"""
    
    def __init__(self):
        self.platform_name = self.get_platform_name()
        self.is_configured = self.check_configuration()
    
    @abstractmethod
    def get_platform_name(self) -> str:
        """获取平台名称"""
        pass
    
    @abstractmethod
    def check_configuration(self) -> bool:
        """检查配置是否完整"""
        pass
    
    @abstractmethod
    async def publish(self, content: str, **kwargs) -> Dict[str, Any]:
        """发布内容到平台"""
        pass
    
    @abstractmethod
    async def delete_post(self, post_id: str) -> bool:
        """删除已发布的内容"""
        pass
    
    @abstractmethod
    async def get_post_status(self, post_id: str) -> Dict[str, Any]:
        """获取发布内容的状态"""
        pass
    
    def validate_content(self, content: str, max_length: int = None) -> bool:
        """验证内容是否符合平台要求"""
        if not content or not content.strip():
            app_logger.warning(f"{self.platform_name}: 内容为空")
            return False
        
        if max_length and len(content) > max_length:
            app_logger.warning(f"{self.platform_name}: 内容超长，当前{len(content)}字符，限制{max_length}字符")
            return False
        
        return True
    
    def format_response(self, success: bool, data: Any = None, error: str = None) -> Dict[str, Any]:
        """格式化响应结果"""
        response = {
            "success": success,
            "platform": self.platform_name,
            "timestamp": datetime.utcnow().isoformat()
        }
        
        if success and data:
            response["data"] = data
        
        if not success and error:
            response["error"] = error
        
        return response
    
    async def test_connection(self) -> bool:
        """测试平台连接"""
        try:
            # 子类可以重写此方法实现具体的连接测试
            return self.is_configured
        except Exception as e:
            app_logger.error(f"{self.platform_name} 连接测试失败: {e}")
            return False